var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var PORT = parseInt(process.argv[2]) || 1234;
var init = 0;
var filepath = './readfile.txt'
var timer = null;

// 初始化文件内容
// writeFileTextForJson(filepath,{index:0,path:''})

console.log('0000')

// 创建server
var server = http.createServer(function (req, res) {

    function error(err) {
        res.writeHead(500, {'Content-Type': 'text/plain'});
        res.end(err.toString()); //fail
    }

    function next(from, to) {
        fs.readFile(from, function (err, content) {
            if (err) {
                error(err);
            } else {
                fs.writeFile(to, content, function (err) {
                    if (err) {
                        error(err);
                    }
                    res.writeHead(200, {'Content-Type': 'text/plain'});
                    res.end('0'); //success
                });
            }
        });
    }

    // 向服务器里写入文件
    function writeBufferFile(to,files){
        fs.exists(to,function(exists){
            if (exists) {
                fs.unlink(to, function (err) {
                    next(files.file.path, to);
                });
            } else {
                fs.exists(path.dirname(to), function (exists) {
                    if (exists) {
                        next(files.file.path, to);
                    } else {
                        mkdirp(path.dirname(to), 0777, function (err) {
                            if (err) {
                                error(err);
                                return;
                            }
                            next(files.file.path, to);
                        });
                    }
                });
            }
        });
    };

    if (req.url == '/') {
        // show a file upload form
        res.writeHead(200, {'content-type': 'text/html'});
        res.end('I\'m ready for that, you know.');
    } else if (req.url == '/receiver' && req.method.toLowerCase() == 'post') {
        var form = new formidable.IncomingForm();
        form.parse(req, function (err, fields, files) {
            if (err) {
                error(err);
            } else {
                var to = fields['to']
                var token = null
                var base = fields['base']
                var exclude = fields['exclude']

                if(base){
                    //表示fis3 发布
                    token=fields['tokens']
                    var reg = new RegExp('\/' + base)
                    to = to.replace(reg,'')
                }else{
                    //表示 webpack  发布
                    to = fields['to']
                    token=fields['token']
                }
                var arr=token.split('/')
                var filename='./'+arr[arr.length-1]+'.txt'

                initFileFofile(writeBufferFile,to,token,files,filename,exclude);
            }
        });
    }
});

// 第一次清除服务器文件  最后一次恢复
function initFileFofile(writeBufferFile,to,token,files,filename,exclude){
    //清除记录 
    clearTimeout(timer)
    var readJson=null;
    readFileTextToJson(filename,token,function(data){
        readJson=data
    
        var index=readJson.index+1;

        writeFileTextForJson(filename,{index:index,path:token});

        timer=setTimeout(function(){
            writeFileTextForJson(filename,{index:0,path:token});
            console.log('----------重写初始化文件只执行一次额-----------！')
        },10000)

        // 清空目录
        if(!readJson.index){
            console.log('--------删除文件只能执行一次额！---------')

            deleteDir(token,exclude,function(){
                // 写入服务器
                writeBufferFile(to,files)
            })
        }else{
            // 写入服务器
            writeBufferFile(to,files)
        }
    });
}


// 写入文件内容函数
function writeFileTextForJson(file,json){
    return fs.writeFileSync(file, JSON.stringify(json));
}

// 读取文件内容函数
function readFileTextToJson(file,token,fn){
    fs.exists(file,function(exists){
        if(!exists){
            console.log("文件不存在就先创建文件夹-------------")
            writeFileTextForJson(file,{index:0,path:token});
        }
        var readJson=JSON.parse(fs.readFileSync(file).toString());
        fn&&fn(readJson)
    })
}

// 删除脚本文件
function deleteDir(mkdir,exclude,fn){
    if(mkdir.indexOf('../html') == -1){
        return false;
    };
    var exec = require('child_process').exec,
        child;
    let shell=null

    if(exclude){
        shell='find "'+mkdir+'" | grep -v "'+exclude+'" | xargs rm -rf'  
    }else{
       shell='rm -rf '+mkdir 
    }
    
    console.log(exclude)

    child = exec(shell,function(err,out) { 
        if(err){
            console.log('-----------删除文件失败!---------------'); 
            console.log(err); 
        };
        fn&&fn()
        console.log('--------------删除文件成功!------------')
    });
};

server.listen(PORT, function () {
    console.log('receiver listening *:' + PORT);
});